interface NewsItem {
  uniquekey: string;
  title: string;
  date: string;
  category: string;
  author_name: string;
  url: string;
  thumbnail_pic_s: string;
}

Page({
  data: {
    newsList: [] as NewsItem[],
    searchQuery: '',
    originalNewsList: [] as NewsItem[] // 用于保存原始的新闻列表数据
  },
  onLoad: function () {
    this.getNews();
  },
  getNews: function () {
    const apiKey = '41d1a37e6c7a5708abe583f533ab2663'; // 替换为你的聚合数据 API Key
    const url = `https://v.juhe.cn/toutiao/index?type=top&key=${apiKey}`;
    
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        if (res.statusCode === 200) {
          try {
            const responseData = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
            if (responseData.error_code === 0) {
              const articles: NewsItem[] = responseData.result.data.map((item: any) => ({
                uniquekey: item.uniquekey,
                title: item.title,
                date: item.date,
                category: item.category,
                author_name: item.author_name,
                url: item.url,
                thumbnail_pic_s: item.thumbnail_pic_s
              }));
              this.setData({
                newsList: articles,
                originalNewsList: articles // 保存原始新闻数据以便重置
              });
              console.log('获取新闻成功：', articles);
            } else {
              console.error('获取新闻失败：', responseData.reason);
            }
          } catch (error) {
            console.error('数据解析失败：', error);
          }
        } else {
          console.error('请求失败，状态码：', res.statusCode);
        }
      },
      fail: (err) => {
        console.error('API请求失败：', err);
      }
    });
  },
  onSearchInput: function (e: any) {
    this.setData({
      searchQuery: e.detail.value
    });
  },
  onSearch: function () {
    if (this.data.searchQuery.trim() === '') {
      // 如果搜索框为空，则重置为原始新闻列表
      this.setData({
        newsList: this.data.originalNewsList
      });
    } else {
      const filteredNews = this.data.originalNewsList.filter(item => 
        item.title.includes(this.data.searchQuery) ||
        item.category.includes(this.data.searchQuery) ||
        item.author_name.includes(this.data.searchQuery)
      );
      this.setData({
        newsList: filteredNews
      });
    }
  },
  goToDetail: function (e: any) {
    const url = e.currentTarget.dataset.url; // 确保正确获取 dataset 中的 url
    console.log('点击的 URL:', url); // 调试：查看点击的 URL

    if (url) {
      wx.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(url)}`,
        success: () => {
          console.log('页面跳转成功');
        },
        fail: (err) => {
          console.error('页面跳转失败:', err); // 确认失败的具体原因
        }
      });
    } else {
      console.error('无效的 URL');
    }
  },
  onResetSearch: function () {
    // 重新设置新闻列表为原始的完整新闻列表
    this.setData({
      newsList: this.data.originalNewsList,
      searchQuery: ''
    });
  }
});
